package org.liquidByte.trafficMustang.androidApp.proxy;

import java.io.UnsupportedEncodingException;

import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.StringEntity;

import com.google.gson.Gson;

class ProxyRequestBuilder {
	private String method;
	private Object param;
	
	String getMethod() {
		return method;
	}
	void setMethod(String method) {
		this.method = method;
	}
	Object getParam() {
		return param;
	}
	void setParam(Object param) {
		this.param = param;
	}
	
	public HttpUriRequest build() throws ProxyRuntimeException {
		if (this.method == null) {
			return null;
		}
		else {
			HttpUriRequest request = null;
			if (this.param != null) {
				request = this.buildRequest(this.param);
			} else {
				request = this.buildRequest();
			}
			return request;
		}
	}
	
	private HttpUriRequest buildRequest(Object param) throws ProxyRuntimeException {
		HttpPost post = new HttpPost(Proxy.encodeUri(this.method));
		
	    post.setHeader("Accept", "application/json");
        post.setHeader("Content-Type", "application/json");
        
        Gson gson = new Gson();
        
        String buffer = gson.toJson(param);
        
        try {
			post.setEntity(new StringEntity(buffer));
		} catch (UnsupportedEncodingException e) {
			throw new ProxyRuntimeException();
		}
        
        return post;
	}
	
	private HttpUriRequest buildRequest() {
		HttpGet get = new HttpGet(Proxy.encodeUri(this.method));
		get.setHeader("Accept", "application/json");
		return get;
	}
}
